extends CharacterBody2D

@export var speed: float = 50.0
@onready var enemy_animation: AnimatedSprite2D = $EnemyAnimation
@onready var nav_agent: NavigationAgent2D = $EnemyNavigationRegion
const SPEED = 50.0
@export var tile_map: TileMapLayer
var move_dir:Vector2

func _ready() -> void:
	init_nav_tilemap()

func _physics_process(delta: float) -> void:
	if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
		nav_agent.target_position = get_global_mouse_position();
	
	if !nav_agent.is_navigation_finished():
		move_dir = position.direction_to(nav_agent.get_next_path_position())
		velocity = move_dir.normalized() * speed
		move_and_slide()
	else:
		velocity = Vector2.ZERO
	handle_ani()
	
func init_nav_tilemap()->void:
	var nav_map:TileMapLayer = get_tree().get("%nav") as TileMapLayer
	if nav_map:
		tile_map = nav_map
		nav_agent.set_navigation_map(nav_map)
	pass
		
func handle_ani()->void:
	if velocity.x < 0:
		enemy_animation.play("walk_left")
	elif velocity.x > 0:
		enemy_animation.play("walk_right")
	else:
		if move_dir.x < 0:
			enemy_animation.play("idle_left")
		else:
			enemy_animation.play("idle_right")
	pass
